package com.example.a2209_shop.fgViewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.CarEntity
import com.example.base.entity.ShopEntity
import com.example.base.entity.ShopEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.get
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class CarViewModel :BaseViewModel(){
    val selectSuccess = MutableLiveData<ShopEntityResult>()
    val selectFail = MutableLiveData<String>()

    fun selectCar(){
        viewModelScope.launch {
            try {
                selectSuccess.value = apiServer.selectCar()
            }catch (e:Exception){
                selectFail.value = e.message
            }
        }
    }
    val addSuccess = MutableLiveData<CarEntity>()
    val addFail = MutableLiveData<String>()

    fun addCar(count:Int,goods_id:Int){
        viewModelScope.launch {
            try {
                Log.d("ssss", "addCar: dcfvgbhnj")
                val map = mutableMapOf<String,Int>()
                map["count"] = count
                map["goods_id"] = goods_id
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                addSuccess.value = apiServer.addCar(body)

            }catch (e:Exception){
                addFail.value = e.message
                Log.i("ssss", "addCar: wdefrgthyujkl")
            }
        }
    }

    val deleteSuccess = MutableLiveData<CarEntity>()
    val deleteFail = MutableLiveData<String>()

    fun deleteCar(ids:String){
        viewModelScope.launch {
            try {
               val map = mutableMapOf<String,String>()
                map["ids"] = ids
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                deleteSuccess.value = apiServer.deleteCar(body)
            }catch (e:Exception){
                deleteFail.value = e.message
            }
        }
    }


    val searchSuccess = MutableLiveData<List<ShopEntity>>()
    val searchFail = MutableLiveData<String>()

    fun search(name:String){
        viewModelScope.launch {
            try {
                val shop = apiServer.selectCar()
                val data = shop.data.filter { it.goods_desc.contains(name) }
                searchSuccess.value = data
            }catch (e:Exception){
                searchFail.value = e.message
            }
        }
    }
}